﻿using System;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RotovapPlatform.UI.ViewModels.DeviceMaintenance.ManualOperation;

namespace RotovapPlatform.UI.Views.DeviceMaintenance.ManualOperation
{
	/// <summary>
	/// RobotControlView.xaml 的交互逻辑
	/// </summary>
	public partial class RobotControlView : UserControl
	{
		private RobotControlViewModel _viewModel;
		private ILogger<RobotControlView> _logger;

		public RobotControlView()
		{
			InitializeComponent();

			// 获取ViewModel和Logger
			_viewModel = App.ServiceProvider.GetRequiredService<RobotControlViewModel>();
			_logger = App.ServiceProvider.GetRequiredService<ILogger<RobotControlView>>();
			DataContext = _viewModel;

			// 注册页面生命周期事件
			Loaded += RobotControlView_Loaded;
			Unloaded += RobotControlView_Unloaded;
		}

		private void RobotControlView_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("RobotControlView页面已加载");

				// 重新初始化ViewModel
				_viewModel.Reinitialize();
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "RobotControlView加载异常");
			}
		}

		private void RobotControlView_Unloaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("RobotControlView页面已卸载");

				// 在页面卸载时释放ViewModel资源
				if (_viewModel is IDisposable disposable)
				{
					disposable.Dispose();
					_logger?.LogInformation("RobotControlViewModel已释放");
				}
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "RobotControlView卸载异常");
			}
		}
	}
}